package com.jxy.homepage.security.jwt;

import com.alibaba.druid.support.json.JSONWriter;
import com.alibaba.fastjson.JSON;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import sun.plugin.liveconnect.SecurityContextHelper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * JwtAuthenticationTokenFilter
 *
 * @author Jxy
 * @date 2022/1/10
 * @Description 实现token验证的过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private static final String URI = "/api/auth/login";
    private static final String BEARER = "Bearer ";
    private final JwtTokenUtils jwtTokenUtils;
    private final JwtSecurityProperties jwtSecurityProperties;

    public JwtAuthenticationTokenFilter(JwtTokenUtils jwtTokenUtils, JwtSecurityProperties jwtSecurityProperties) {
        this.jwtTokenUtils = jwtTokenUtils;
        this.jwtSecurityProperties = jwtSecurityProperties;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String bearerToken = request.getHeader(jwtSecurityProperties.getHeader());
        String uri = request.getRequestURI();
        if (URI.equals(uri)) {
            filterChain.doFilter(request, response);
            return;
        }
        String token;
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(BEARER)) {
            token = bearerToken.substring(BEARER.length());
            // 认证成功
            if (StringUtils.hasText(token) && jwtTokenUtils.verifyToken(token) > 0) {
                Authentication authentication = this.jwtTokenUtils.getAuthentication(token);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(request, response);
    }
}
